/* eslint-disable @typescript-eslint/explicit-function-return-type */

import AsyncStorage from '@react-native-community/async-storage';
import { GetRoomInfoRes } from '../api/class/getRoomInfo';
import { RoundInfo } from '../api/class/getRoundList';
import { STORAGE_KEY_CLASSROOM } from '../constant';
import {
  ClassRoomType,
  LessonStatus,
  ProblemRoundStatus,
  RoundType,
  UserRole
} from '../pages/ClassRoom/constant';
import { getUserInfo } from './user';

export interface CurrentRound {
  roundId: number;
  roundType: number;
  roundProgress?: number;
  discussProgress?: number;
  doProblemProgress?: number;
  explainVideoProgress?: number;
  roundStatus?: number;
}

export interface VodRoomInfos {
  [key: number]: {
    userGoldCoinNum: number;
    currentRound: CurrentRound | null;
    duration: number;
  };
}

let vodRoomInfos: VodRoomInfos = {};
let timer: NodeJS.Timer | null;

AsyncStorage.getItem(STORAGE_KEY_CLASSROOM).then((res: any): void => {
  if (res) {
    vodRoomInfos = JSON.parse(res);
  }
});

export const asyncClassRoomStorage = (data: VodRoomInfos): void => {
  AsyncStorage.setItem(STORAGE_KEY_CLASSROOM, JSON.stringify(data));
};

export const startAsyncClassRoomInfo = (): void => {
  asyncClassRoomStorage(vodRoomInfos);
  timer = setInterval((): void => {
    asyncClassRoomStorage(vodRoomInfos);
  }, 60 * 1000);
};

export const endAsyncClassRoomInfo = (): void => {
  asyncClassRoomStorage(vodRoomInfos);
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

export const updateUserGoldCoinNum = (
  lessonId: number,
  type: ClassRoomType
) => (n: number): void => {
  if (type !== ClassRoomType.Vod) return;
  if (vodRoomInfos[lessonId]) {
    vodRoomInfos[lessonId].userGoldCoinNum = n;
  }
};

export const updateCurrentRoundInfo = (
  lessonId: number,
  type: ClassRoomType
) => (round: CurrentRound): void => {
  if (type !== ClassRoomType.Vod) return;
  if (vodRoomInfos[lessonId]) {
    vodRoomInfos[lessonId].currentRound = round;
  }
};

export const updateClassRoomDuration = (
  lessonId: number,
  type: ClassRoomType
) => (d: number): void => {
  if (type !== ClassRoomType.Vod) return;
  if (vodRoomInfos[lessonId]) {
    vodRoomInfos[lessonId].duration = d;
  }
};

export const clearRoomInfo = (lessonId: number): void => {
  if (vodRoomInfos[lessonId]) {
    vodRoomInfos[lessonId].userGoldCoinNum = 0;
    vodRoomInfos[lessonId].currentRound = null;
    vodRoomInfos[lessonId].duration = 0;
  }
};

export const classRoomHaveVodRecordWithLessonId = (
  lessonId: number
): boolean => {
  return !!(vodRoomInfos[lessonId] && vodRoomInfos[lessonId].currentRound);
};

export const getRoomInfo = (lessonId: number) => (
  startRound: RoundInfo
): Promise<GetRoomInfoRes> => {
  const { roundId: startRoundId, roundType: startRoundType } = startRound;

  let startRoundStatus = ProblemRoundStatus.Analysis;
  if (startRoundType === RoundType.Problem) {
    startRoundStatus = ProblemRoundStatus.DoProblemAfterDiscuss;
  }
  if (!vodRoomInfos[lessonId]) {
    vodRoomInfos[lessonId] = {
      userGoldCoinNum: 0,
      currentRound: {
        roundId: startRoundId,
        roundType: startRoundType,
        roundProgress: 0,
        discussProgress: 0,
        doProblemProgress: 0,
        explainVideoProgress: 0,
        roundStatus: startRoundStatus
      },
      duration: 0
    };
  }
  const { userGoldCoinNum, currentRound } = vodRoomInfos[lessonId];
  const {
    roundId = startRoundId,
    roundType = startRoundType,
    roundProgress = 0,
    doProblemProgress = 0,
    explainVideoProgress = 0,
    roundStatus = startRoundStatus
  } = currentRound || {};
  const { userId, role, nickName } = getUserInfo();
  const userInfo = {
    userId,
    userRole: role || UserRole.Student,
    userNickName: nickName,
    goldCoinNum: userGoldCoinNum,
    headUrl: ''
  };

  return new Promise((resolve, reject): void => {
    resolve({
      code: 0,
      data: {
        channel: '', // 写死为空即可，没有用到
        users: [userInfo], // 需要初始化为当前用户（userId, userRole, goldCoinNum, userNickName）
        lessonStatus: LessonStatus.HaveStart, // 写死已经开始即可，课程结束会直接清缓存
        currentRoundInfo: {
          roundId,
          roundType,
          roundProgress,
          doProblemProgress,
          explainVideoProgress,
          roundStatus,
          submitProblemUsers: [] // 写死为空数组即可
        },
        lessonName: '', // 房间没有用到
        lessonStartTime: '', // 房间没有用到
        intervalBeforeLessonStart: 0, // 距离课程开始还有多长时间
        isAssistTalk: false,
        leftTalkDuration: 0,
        maxTalkDuration: 60 * 1000,
        startImageURL: '',
        startVideoURL: '',
        bigClassChannel: ''
      },
      msg: '',
      traceId: ''
    });
  });
};

export const getReplayDuration = (lessonId: number): number => {
  return vodRoomInfos[lessonId] ? vodRoomInfos[lessonId].duration : 0;
};
